<template>
  <div class="bannerAdd">
    <div class="input">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="轮播图名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="轮播图排序">
          <el-input-number
            v-model="ruleForm.sort"
            class="mx-4"
            :min="0"
            :max="10"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="链接地址">
          <el-input v-model="ruleForm.addres" />
        </el-form-item>
        <el-form-item label="轮播图图片" prop="banner">
            <el-upload
            class="avatar-uploader"
            :action="uploadUrl + '/oss/upload-img'"
            :data="{ cateDir: 'course' }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <!-- 其他表单项 -->
      </el-form>
      <el-button
        type="primary"
        style="margin-left: 80px"
        @click="submitForm(ruleFormRef)"
        >提交</el-button
      >
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { reactive, ref } from "vue";
import type {
  UploadFile,
  FormInstance,
  FormRules,
  UploadProps,
} from "element-plus";
//导入工具 - 密码校验
import { ElMessage } from "element-plus";
import axios from "../../assets/js/axios";

const route = useRoute();
const router = useRouter();
//接收传递过来的id
if (route.query.id) {
  //修改元信息标题
  console.log("id:", route.query.id);
  route.meta.title = "常用管理/轮播图管理/轮播图编辑";
  // 发送请求显示编辑的用户信息
  axios
    .get("/serviceedu/edu-banner/getById/" + route.query.id, {})
    .then((res: any) => {
      console.log(res);
      ruleForm.id = res.data.data.id;
      ruleForm.name = res.data.data.name;
      ruleForm.sort = res.data.data.sort;
      ruleForm.addres = res.data.data.addres;
      ruleForm.banner = res.data.data.banner;
      imageUrl.value = res.data.data.banner;
    });
}

interface RuleForm {
  id?: number;
  name: string;
  sort: number;
  addres: string;
  banner: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  name: "",
  sort: 0,
  addres: "",
  banner: "",
});

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: "请输入轮播图名称", trigger: "blur" },
    { min: 2, max: 20, message: "轮播图名称2-20个字符长度", trigger: "blur" },
  ],
  sort: [{ required: true, message: "请输入昵称", trigger: "blur" }],

  addres: [{ required: true, message: "请选择轮播图地址", trigger: "blur" }],
  banner: [{ required: true, message: "请输入轮播图图片", trigger: "blur" }],
});
// 上传头像
const imageUrl = ref("");
const uploadUrl = import.meta.env.VITE_URL;
// 文件上传成功的方法
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  console.log("response:", response);
  imageUrl.value = response.data.url;
  ruleForm.banner = response.data.url;
};

//点击保存
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!", ruleForm);

      if (route.query.id) {
        // 进行保存修改
        axios
          .put("/serviceedu/edu-banner/updateBanner", ruleForm)
          .then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: "修改用户成功",
              });
              // 跳转用户列表页
              router.push("/bannerList");
            }
          });
      } else {
        // 进行保存新增
        // 发送axios请求保存用户数据
        axios
          .post("/serviceedu/edu-banner/addBanner", ruleForm)
          .then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                type: "success",
                message: "保存用户成功",
              });
              // 跳转用户列表页
              router.push("/bannerList");
            }
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>
  
  <style lang="less" scoped>
.bannerAdd {
  
    :deep .avatar-uploader {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed #cccccc;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: #409eff;
    }
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
  